import router from "./router";
import dyroutes from './router/dyroutes'
import store from './store'
import DataStore from '@/utils/store'

const sessionStore = new DataStore()

// 刷新页面，此文件会重新执行
store.commit('user/setUserLoginInfo', {
  token: sessionStore.get('token'),
  nickname: sessionStore.get('nickname'),
  routes: sessionStore.get('routes'),
  roleid: sessionStore.get('roleid'),
})

// 路由守卫
router.beforeEach((to, from, next) => {
  let adminRoute = router.options.routes[0]
  // 第1次添加进去
  // 这个判断一定要加，否则会有死循环
  if (to.path !== '/login' && adminRoute.children.length === 0) {
    let newRoutes = dyroutes.filter(item => store.getters.routes.includes('/admin/' + item.path))
    adminRoute.children.unshift(...newRoutes)
    // 动态添加一个新的路由
    router.addRoute(adminRoute);
    // 重定向,为了让刚刚添加的路由规则生效
    next({
      path: to.path,
      replace: true
    })
  } else {
    next()
  }
})